package com.spcmg.service.impl;

import com.spcmg.mapper.SpcRoomMapper;
import com.spcmg.service.ISpcMgDownloadService;
import com.spcmg.utils.DateUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Service
public class SpcMgDownloadServiceImpl implements ISpcMgDownloadService {

    @Resource
    private SpcRoomMapper spcRoomMapper;

    @Override
    public void download(HttpServletResponse res) throws Exception {
        // 查询所有机房所有数据
        List<Map<String, Object>> dataMapList = spcRoomMapper.selectAllForDownload();
        StringBuilder sb = new StringBuilder("机房ID,机房名称,所属局站名称,机房地址,经度,纬度,机房等级,机房类型,投产时间\n");
        for (Map<String, Object> dataMap : dataMapList) {
            sb.append(MapUtils.getLong(dataMap, "ROOM_ID")).append(",");
            sb.append(MapUtils.getString(dataMap, "CHINA_NAME")).append(",");
            sb.append(MapUtils.getString(dataMap, "STATION_NAME")).append(",");
            sb.append(MapUtils.getString(dataMap, "ADDRESS")).append(",");
            BigDecimal x = new BigDecimal(MapUtils.getString(dataMap, "X"));
            BigDecimal y = new BigDecimal(MapUtils.getString(dataMap, "Y"));
            sb.append(x.setScale(6, RoundingMode.HALF_DOWN)).append(",");
            sb.append(y.setScale(6, RoundingMode.HALF_DOWN)).append(",");
            sb.append(MapUtils.getString(dataMap, "CLASS_ID")).append(",");
            sb.append(MapUtils.getString(dataMap, "TYPE_ID")).append(",");
            sb.append(MapUtils.getString(dataMap, "START_USE_DATE")).append("\n");
        }

        byte[] bs = sb.toString().getBytes("utf-8");
        res.reset();
//        res.setContentType("application/octet-stream");
        res.setContentType("application/force-download");
//        res.addHeader("filename", URLEncoder.encode("机房导出-" + DateUtil.formatNow("yyyy-MM-dd") + ".csv", "UTF-8"));
        res.setHeader("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode("机房导出-" + DateUtil.formatNow("yyyy-MM-dd") + ".csv", "UTF-8"));
        OutputStream out = res.getOutputStream();
        out.write(bs, 0, bs.length);
        out.flush();
    }
}
